package com.kucowka.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import com.kucowka.db.entities.User;

@Aspect
@Component
public class LogingAspect {

	private Logger logger = Logger.getLogger(LogingAspect.class);

	@Before("execution(public * com.kucowka.db.service.*..*(..))")
	public void logServiceInvocation() {
		logger.debug("Service method invoked...");
	}

	@Around("execution(* com.kucowka.db.service.UserServiceImpl.createUser(*)) && args(user)")
	public void calculateMethodInvocationTime(ProceedingJoinPoint pjp, User user)
			throws Throwable {

		StopWatch stopWatch = new StopWatch("UserServiceImpl.removeUser");
		stopWatch.start();
		try {
			user.setEmail("franek@com.pl");
			pjp.proceed();
		} finally {
			stopWatch.stop();
			logger.debug("Invocation took: " + stopWatch.getTotalTimeMillis()
					+ " ms");
		}
	}

	@Before("@annotation(org.springframework.transaction.annotation.Transactional)")
	public void registerTransactionStart() {
		logger.debug("New transaction started");
	}

	@After("@annotation(org.springframework.transaction.annotation.Transactional)")
	public void registerTransactionEnd() {
		logger.debug("New transaction finished");
	}

	@Before("@target(org.springframework.stereotype.Component) && execution(String com.kucowka.db.service.UserServiceImpl.getServiceDescription(..)) && " +  
			"args(i, *)")
	public void testingGetServiceDescriptionMethod(Long i) {
		logger.debug("getServiceDescription invoked with first argument l equal: "
				+ i);
	}

}
